import consola from 'consola'
import config from '../../../nuxt.config'
import sequelize from '../database/sequelize'
import { Nuxt, Builder } from 'nuxt'
import { generateKey } from '../utils/key'

module.exports = app => {
  const { isDev, env } = app.config.commonConfig
  sequelize
    .sync({ force: false })
    .then(async () => {
      const host = process.env.HOST || '127.0.0.1'
      const port = process.env.PORT || 3000
      const nuxt = new Nuxt(config)
      config.dev = isDev
      app.set('port', port)

      // 生产密钥对
      await generateKey()

      // DEV环境，构建NUXT
      if (config.dev) {
        const builder = new Builder(nuxt)
        await builder.build()
      }

      app.use(nuxt.render)
      app.listen(port, host)
      consola.ready({
        message: `数据库连接成功，服务启动成功【${env}】：http://${host}:${port}`,
        badge: true
      })
    })
    .catch(error => {
      console.log(error.message)
      consola.error({
        message: `连接数据库失败【${env}】`,
        badge: true
      })
    })
}
